import React, { useState } from "react";
import {
  Card,
  Tabs,
  Form,
  Input,
  Button,
  Avatar,
  Upload,
  message,
  Descriptions,
  Divider,
  Select,
  Tag,
  Space,
} from "antd";
import {
  UserOutlined,
  UploadOutlined,
  EditOutlined,
  SaveOutlined,
  CloseOutlined,
  MessageOutlined,
} from "@ant-design/icons";
import { useUser } from "../../contexts/UserContext";
import { authAPI } from "../../services/api";
import styled from "styled-components";

// 根据用户角色生成默认头像
const getDefaultAvatar = (name: string, role: string) => {
  // 使用姓名的hash值作为种子，避免中文编码问题
  const hash = name.split('').reduce((a, b) => {
    a = ((a << 5) - a) + b.charCodeAt(0);
    return a & a;
  }, 0);
  const seed = Math.abs(hash).toString();
  
  // 根据角色设置不同的卡通头像样式
  let avatarUrl;
  if (role === "teacher") {
    // 教师使用更成熟的卡通风格
    avatarUrl = `https://api.dicebear.com/7.x/adventurer/svg?seed=${seed}&backgroundColor=b6e3f4`;
  } else if (role === "admin") {
    // 管理员使用权威的卡通风格
    avatarUrl = `https://api.dicebear.com/7.x/adventurer/svg?seed=${seed}&backgroundColor=ffcdd2`;
  } else {
    // 学生使用活泼的卡通风格
    avatarUrl = `https://api.dicebear.com/7.x/personas/svg?seed=${seed}&backgroundColor=ffdfbf`;
  }
  
  console.log(`生成头像: ${name} (${role}) -> ${avatarUrl}`);
  return avatarUrl;
};

const { TabPane } = Tabs;

const ProfileContainer = styled.div`
  max-width: 900px;
  margin: 0 auto;
  padding: 24px;
`;

const AvatarContainer = styled.div`
  text-align: center;
  margin-bottom: 24px;
`;

const InfoCard = styled(Card)`
  margin-bottom: 16px;

  .ant-card-head {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;

    .ant-card-head-title {
      color: white;
    }
  }
`;

// 支持外部传入user（如资料卡片弹窗），否则默认用当前登录用户
interface UserProfileProps {
  user?: import("../../contexts/UserContext").User;
  cardMode?: boolean; // 是否为卡片弹窗模式
  onChat?: (userId: string) => void; // 私聊按钮回调
}

const UserProfile: React.FC<UserProfileProps> = ({ user: propUser, cardMode, onChat }) => {
  const { user: contextUser, refreshAuth } = useUser();
  const user = propUser || contextUser;
  const [loading, setLoading] = useState(false);
  const [editingBasic, setEditingBasic] = useState(false);
  const [editingRole, setEditingRole] = useState(false);
  const [basicForm] = Form.useForm();
  const [roleForm] = Form.useForm();
  const [passwordForm] = Form.useForm();

  const handleBasicInfoSubmit = async (values: any) => {
    try {
      setLoading(true);
      console.log("更新基本信息:", values);

      // TODO: 调用更新用户信息的API
      // const { authAPI } = await import("../../services/apiService");
      // await authAPI.updateProfile(values);

      // 模拟API调用成功，刷新用户信息
      await refreshAuth();

      message.success("个人信息更新成功");
      setEditingBasic(false);
    } catch (error) {
      console.error("更新基本信息失败:", error);
      message.error("更新失败，请重试");
    } finally {
      setLoading(false);
    }
  };

  const handleRoleInfoSubmit = async (values: any) => {
    try {
      setLoading(true);
      console.log("更新角色信息:", values);

      // TODO: 调用更新角色信息的API
      // const { authAPI } = await import("../../services/apiService");
      // await authAPI.updateRoleInfo(values);

      // 模拟API调用成功，刷新用户信息
      await refreshAuth();

      message.success("角色信息更新成功");
      setEditingRole(false);
    } catch (error) {
      console.error("更新角色信息失败:", error);
      message.error("更新失败，请重试");
    } finally {
      setLoading(false);
    }
  };

  const handlePasswordSubmit = async (values: any) => {
    try {
      setLoading(true);
      console.log("修改密码:", { currentPassword: "***", newPassword: "***" });

      // TODO: 调用修改密码的API
      // const { authAPI } = await import("../../services/apiService");
      // await authAPI.changePassword({
      //   currentPassword: values.currentPassword,
      //   newPassword: values.newPassword
      // });

      message.success("密码修改成功");
      passwordForm.resetFields();
    } catch (error) {
      console.error("修改密码失败:", error);
      message.error("修改失败，请重试");
    } finally {
      setLoading(false);
    }
  };

  const handleAvatarUpload = async (file: File) => {
    try {
      setLoading(true);
      console.log("上传头像:", file.name);

      // TODO: 调用上传头像API
      // const { fileAPI } = await import("../../services/apiService");
      // const uploadResult = await fileAPI.uploadAvatar(file);
      // await authAPI.updateProfile({ avatar: uploadResult.url });

      // 模拟成功，刷新用户信息
      await refreshAuth();

      message.success("头像上传成功");
    } catch (error) {
      console.error("头像上传失败:", error);
      message.error("头像上传失败");
    } finally {
      setLoading(false);
    }
  };

  const getRoleTag = (role: string) => {
    const roleMap: { [key: string]: { text: string; color: string } } = {
      admin: { text: "管理员", color: "red" },
      teacher: { text: "教师", color: "blue" },
      student: { text: "学生", color: "green" },
    };
    return (
      <Tag color={roleMap[role]?.color || "default"}>
        {roleMap[role]?.text || role}
      </Tag>
    );
  };

  const renderRoleSpecificInfo = () => {
    if (!user) return null;

    if (user.role === "teacher") {
      return (
        <InfoCard
          title="教师信息"
          size="small"
          extra={
            <Button
              type="text"
              icon={editingRole ? <CloseOutlined /> : <EditOutlined />}
              onClick={() => {
                setEditingRole(!editingRole);
                if (editingRole) {
                  roleForm.resetFields();
                }
              }}
              style={{ color: "white" }}
            >
              {editingRole ? "取消" : "编辑"}
            </Button>
          }
        >
          {editingRole ? (
            <Form
              form={roleForm}
              layout="vertical"
              initialValues={{
                department: user.department,
                title: user.title,
                subject: user.subject,
                teacherNo: user.teacherNo,
              }}
              onFinish={handleRoleInfoSubmit}
            >
              <Form.Item label="工号" name="teacherNo">
                <Input placeholder="请输入教师工号" disabled />
              </Form.Item>
              <Form.Item label="所属院系" name="department">
                <Input placeholder="如：计算机学院" />
              </Form.Item>
              <Form.Item label="职称" name="title">
                <Select placeholder="请选择职称">
                  <Select.Option value="助教">助教</Select.Option>
                  <Select.Option value="讲师">讲师</Select.Option>
                  <Select.Option value="副教授">副教授</Select.Option>
                  <Select.Option value="教授">教授</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item label="主要学科" name="subject">
                <Input placeholder="如：计算机科学与技术" />
              </Form.Item>
              <Form.Item>
                <Space>
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={loading}
                    icon={<SaveOutlined />}
                  >
                    保存
                  </Button>
                  <Button onClick={() => setEditingRole(false)}>取消</Button>
                </Space>
              </Form.Item>
            </Form>
          ) : (
            <Descriptions column={2} size="small">
              <Descriptions.Item label="工号">
                {user.teacherNo || "未设置"}
              </Descriptions.Item>
              <Descriptions.Item label="所属院系">
                {user.department || "未设置"}
              </Descriptions.Item>
              <Descriptions.Item label="职称">
                {user.title || "未设置"}
              </Descriptions.Item>
              <Descriptions.Item label="主要学科" span={2}>
                {user.subject || "未设置"}
              </Descriptions.Item>
            </Descriptions>
          )}
        </InfoCard>
      );
    } else if (user.role === "student") {
      return (
        <InfoCard
          title="学生信息"
          size="small"
          extra={
            <Button
              type="text"
              icon={editingRole ? <CloseOutlined /> : <EditOutlined />}
              onClick={() => {
                setEditingRole(!editingRole);
                if (editingRole) {
                  roleForm.resetFields();
                }
              }}
              style={{ color: "white" }}
            >
              {editingRole ? "取消" : "编辑"}
            </Button>
          }
        >
          {editingRole ? (
            <Form
              form={roleForm}
              layout="vertical"
              initialValues={{
                studentId: user.studentId,
                major: user.major,
                className: user.className,
                grade: user.grade,
              }}
              onFinish={handleRoleInfoSubmit}
            >
              <Form.Item label="学号" name="studentId">
                <Input placeholder="请输入学号" />
              </Form.Item>
              <Form.Item label="专业" name="major">
                <Input placeholder="如：计算机科学与技术" />
              </Form.Item>
              <Form.Item label="班级" name="className">
                <Input placeholder="如：计科21-1班" />
              </Form.Item>
              <Form.Item label="年级" name="grade">
                <Select placeholder="请选择年级">
                  <Select.Option value="2021">2021级</Select.Option>
                  <Select.Option value="2022">2022级</Select.Option>
                  <Select.Option value="2023">2023级</Select.Option>
                  <Select.Option value="2024">2024级</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item>
                <Space>
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={loading}
                    icon={<SaveOutlined />}
                  >
                    保存
                  </Button>
                  <Button onClick={() => setEditingRole(false)}>取消</Button>
                </Space>
              </Form.Item>
            </Form>
          ) : (
            <Descriptions column={2} size="small">
              <Descriptions.Item label="学号">
                {user.studentId || "未设置"}
              </Descriptions.Item>
              <Descriptions.Item label="专业">
                {user.major || "未设置"}
              </Descriptions.Item>
              <Descriptions.Item label="班级">
                {user.className || "未设置"}
              </Descriptions.Item>
              <Descriptions.Item label="年级">
                {user.grade ? `${user.grade}级` : "未设置"}
              </Descriptions.Item>
            </Descriptions>
          )}
        </InfoCard>
      );
    }
    return null;
  };

  return (
    <ProfileContainer>
      <Card>
        {/* 卡片模式下显示私聊按钮 */}
        {cardMode && user && (
          <div style={{ textAlign: "right", marginBottom: 8 }}>
            <Button type="primary" icon={<MessageOutlined />} onClick={() => onChat?.(user.id)}>
              私聊
            </Button>
          </div>
        )}
        <AvatarContainer>
          <Upload
            name="avatar"
            showUploadList={false}
            beforeUpload={async (file) => {
              const isJpgOrPng =
                file.type === "image/jpeg" || file.type === "image/png";
              if (!isJpgOrPng) {
                message.error("只能上传 JPG/PNG 格式的图片！");
                return false;
              }
              const isLt2M = file.size / 1024 / 1024 < 2;
              if (!isLt2M) {
                message.error("图片大小不能超过 2MB！");
                return false;
              }
              await handleAvatarUpload(file);
              return false;
            }}
          >
            <div style={{ position: "relative", display: "inline-block" }}>
              <Avatar
                size={100}
                icon={<UserOutlined />}
                src={user?.avatar || (user ? getDefaultAvatar(user.name, user.role) : undefined)}
                style={{ cursor: "pointer" }}
              />
              <div
                style={{
                  position: "absolute",
                  bottom: 0,
                  right: 0,
                  background: "#fff",
                  borderRadius: "50%",
                  padding: 4,
                  boxShadow: "0 2px 8px rgba(0,0,0,0.15)",
                }}
              >
                <UploadOutlined />
              </div>
            </div>
          </Upload>
          <div style={{ marginTop: 16 }}>
            <h3>{user?.name}</h3>
            {getRoleTag(user?.role || "")}
          </div>
        </AvatarContainer>

        <Tabs defaultActiveKey="overview">
          <TabPane tab="概览" key="overview">
            <InfoCard title="基本信息" size="small">
              <Descriptions column={2} size="small">
                <Descriptions.Item label="用户ID">{user?.id}</Descriptions.Item>
                <Descriptions.Item label="角色">
                  {getRoleTag(user?.role || "")}
                </Descriptions.Item>
                <Descriptions.Item label="姓名">{user?.name}</Descriptions.Item>
                <Descriptions.Item label="手机号">{user?.phone}</Descriptions.Item>
                <Descriptions.Item label="邮箱" span={2}>
                  {user?.email}
                </Descriptions.Item>
                <Descriptions.Item label="简介" span={2}>
                  {user?.bio || "未填写"}
                </Descriptions.Item>
                <Descriptions.Item label="头像" span={2}>
                  {user?.avatar ? (
                    <Avatar src={user.avatar} />
                  ) : user ? (
                    <Avatar src={getDefaultAvatar(user.name, user.role)} />
                  ) : (
                    "未上传"
                  )}
                </Descriptions.Item>
              </Descriptions>
            </InfoCard>

            {renderRoleSpecificInfo()}
          </TabPane>

          <TabPane tab="编辑资料" key="basic">
            <InfoCard title="基本信息编辑" size="small">
              <Form
                form={basicForm}
                layout="vertical"
                initialValues={{
                  name: user?.name,
                  email: user?.email,
                  phone: user?.phone,
                }}
                onFinish={handleBasicInfoSubmit}
              >
                <Form.Item
                  label="姓名"
                  name="name"
                  rules={[{ required: true, message: "请输入姓名" }]}
                >
                  <Input />
                </Form.Item>
                <Form.Item
                  label="邮箱"
                  name="email"
                  rules={[
                    { required: true, message: "请输入邮箱" },
                    { type: "email", message: "请输入有效的邮箱地址" },
                  ]}
                >
                  <Input />
                </Form.Item>
                <Form.Item
                  label="手机号"
                  name="phone"
                  rules={[
                    { required: true, message: "请输入手机号" },
                    { pattern: /^1\d{10}$/, message: "请输入有效的手机号" },
                  ]}
                >
                  <Input />
                </Form.Item>
                <Form.Item>
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={loading}
                    icon={<SaveOutlined />}
                  >
                    保存修改
                  </Button>
                </Form.Item>
              </Form>
            </InfoCard>
          </TabPane>

          <TabPane tab="修改密码" key="password">
            <InfoCard title="密码修改" size="small">
              <Form
                form={passwordForm}
                layout="vertical"
                onFinish={handlePasswordSubmit}
              >
                <Form.Item
                  label="当前密码"
                  name="currentPassword"
                  rules={[{ required: true, message: "请输入当前密码" }]}
                >
                  <Input.Password />
                </Form.Item>
                <Form.Item
                  label="新密码"
                  name="newPassword"
                  rules={[
                    { required: true, message: "请输入新密码" },
                    { min: 6, message: "密码长度不能小于6位" },
                  ]}
                >
                  <Input.Password />
                </Form.Item>
                <Form.Item
                  label="确认新密码"
                  name="confirmPassword"
                  dependencies={["newPassword"]}
                  rules={[
                    { required: true, message: "请确认新密码" },
                    ({ getFieldValue }) => ({
                      validator(_, value) {
                        if (!value || getFieldValue("newPassword") === value) {
                          return Promise.resolve();
                        }
                        return Promise.reject(
                          new Error("两次输入的密码不一致")
                        );
                      },
                    }),
                  ]}
                >
                  <Input.Password />
                </Form.Item>
                <Form.Item>
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={loading}
                    icon={<SaveOutlined />}
                  >
                    修改密码
                  </Button>
                </Form.Item>
              </Form>
            </InfoCard>
          </TabPane>
        </Tabs>
      </Card>
    </ProfileContainer>
  );
};

export default UserProfile;
